package com.matrix.java.util;

import java.util.Arrays;

/**
 *     数组工具类
 */

public class ArrayUtil {
    private ArrayUtil() {
    }
    /**
     * 数组最大元素
     */
    public static int findMaxInArray(int[] array) {
        int max = array[0];
        for (int j : array) {
            max = Math.max(j, max);
        }
        return max;
    }

    /**
     * 数组去重(已排序)
     */
    public static int[] arrayUnrepeated(int... array) {
        int t = 0;
        int[] tempArray = new int[array.length];//临时数组
        for (int i = 0; i < array.length; i++) {
            boolean isRepeat = true;
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] == array[j]) {
                    isRepeat = false;
                    break;
                }
            }
            if (isRepeat){
                tempArray[t] = array[i];
                t++;
            }
        }
        int[] unrepeatedArray = new int[t];//去重数组
        System.arraycopy(tempArray,0,unrepeatedArray,0,t);
        Arrays.sort(unrepeatedArray);
        return unrepeatedArray;
    }
    /**
     * 数组元素计数
     */
    public static int[] arrayElementCount(int... array){
        int[] arrayUnrepeated = ArrayUtil.arrayUnrepeated(array);
        int[] countArr = new int[arrayUnrepeated.length];
        for (int i = 0; i < arrayUnrepeated.length; i++) {
            for (int k : array) {
                if (arrayUnrepeated[i] == k) {
                    countArr[i]++;
                }
            }
        }
        return countArr;
    }
    /**
     * 数组平均值
     */
    public static int average(int[] array){
        int sum = 0;
        for (int j : array) {
            sum += j;
        }
        return sum/ array.length;
    }
    public static double average(double[] array){
        double sum = 0;
        for (double j : array) {
            sum += j;
        }
        return sum/ array.length;
    }
    /**
     * 数组最小元素
     */
    public static double findMinInArray(double[] array) {
        double min = array[0];
        for (double j : array) {
            min = Math.min(j, min);
        }
        return min;
    }

    public static int findMinInArray(int[] array) {
        int min = array[0];
        for (double j : array) {
            min = (int) Math.min(j, min);
        }
        return min;
    }
    public static int findMinSubInArray(double[] array) {
        double min = array[0];
        int minSub =0;
        for (int i = 0; i < array.length; i++) {
            if (array[i]<=min){
                min=array[i];
                minSub = i;
            }
        }
        return minSub;
    }
}
